package com.retail.report.client.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.retail.core.entity.result.Result;
import com.retail.order.entity.vo.RetailOrderDailyStasticsVo;
import com.retail.order.service.RetailSettleOrderService;
import com.retail.report.client.ReportClient;
import com.retail.report.entity.request.ResportRequest;
import com.retail.shop.entity.vo.ShopTypeStasticVo;
import com.retail.shop.service.RetailShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class ReportClientImpl implements ReportClient {

    @Autowired
    private RetailSettleOrderService retailSettleOrderService;
    
    @Autowired
    private RetailShopService retailShopService;


    @Override
    public Result<Map<String, Object>> orderListReport(ResportRequest request) {
        Map<String, Object> res = new HashMap<>();
        if (ObjectUtil.isEmpty(request.getReportMonth())) {
            request.setReportMonth(DateUtil.format(new Date(), "yyyy-MM"));
        }

        // 统计数据 （类别分别情况）
        myOrderReport(request, res);

        // 每日订单数据
        myDailyOrderReport(request, res);

        return Result.success(res);
    }

    @Override
    public Result<Map<String, Object>> statisticsShopReport(ResportRequest request) {
        Map<String, Object> res = new HashMap<>();
        if (ObjectUtil.isEmpty(request.getReportMonth())) {
            request.setReportMonth(DateUtil.format(new Date(), "yyyy-MM"));
        }

        // 统计数据 （类别分别情况）
        myShopTypeReport(request, res); 


        return Result.success(res);
    }

    /**
     * 我的订单统计（只统计个人）
     *
     * @param request
     * @param res
     */

    private void myShopTypeReport(ResportRequest request, Map<String, Object> res) {
        Long adminId = request.getAdminId();
        Integer adminType = request.getAdminType();
        String reportMonth = request.getReportMonth();

        String startMonth = reportMonth + "-01";
        Date startTime = DateUtil.parse(startMonth, "yyyy-MM-dd");
        Date endTime = DateUtil.endOfMonth(startTime);

        Long startTimestamp = startTime.getTime() / 1000;
        Long endTimestamp = endTime.getTime() / 1000;


        List<ShopTypeStasticVo> stasticsOrderWallet = retailShopService.getShopMonthStastics(adminId, startMonth, DateUtil.format(endTime, "yyyy-MM-dd"));
        
        List<String> category = new ArrayList<>();
        category.add("合计");
        category.add("待审核");
        category.add("审核通过");
        category.add("审核不通过");
        
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("categories", category);
        List<Map<String, Object>> data = new ArrayList<>();
        stasticsOrderWallet.forEach(s -> {
            Map<String, Object> inMap = new HashMap<>();
            inMap.put("name", s.getSource() == 0 ?"抖音":
                    s.getSource() == 1 ? "美图": 
                            s.getSource() == 2 ? "系统自建": s.getSource());
            List<Integer> d = new ArrayList<>();
            d.add(s.getShopTypeCount());
            d.add(s.getTobeCount());
            d.add(s.getSuccessCount());
            d.add(s.getFailCount());
            inMap.put("data", d);

            if (ObjectUtil.isNotEmpty(s.getSource())) {
                data.add(inMap);
            }
        });
        resMap.put("series",data);
        
        res.put("shopTypeStasticList", resMap);
    }
    
    
    /**
     * 我的订单统计（只统计个人）
     *
     * @param request
     * @param res
     */

    private void myOrderReport(ResportRequest request, Map<String, Object> res) {
        Long adminId = request.getAdminId();
        Integer adminType = request.getAdminType();
        String reportMonth = request.getReportMonth();

        String startMonth = reportMonth + "-01";
        Date startTime = DateUtil.parse(startMonth, "yyyy-MM-dd");
        Date endTime = DateUtil.endOfMonth(startTime);

        Long startTimestamp = startTime.getTime() / 1000;
        Long endTimestamp = endTime.getTime() / 1000;


        Map<String, Object> stasticsOrderWallet = retailSettleOrderService.getOrderMonthStastics(adminId, adminType, startTimestamp, endTimestamp);

        // 订单统计
        res.put("stasticsOrderWallet", stasticsOrderWallet);

        List<Map<String, Object>> orderStatus = new ArrayList<>();
        Map<String, Object> waitPay = new HashMap<>();
        waitPay.put("name", "待支付");
        waitPay.put("value", stasticsOrderWallet.get("waitpay_count"));
//        waitPay.put("labelText", "待支付:"+ stasticsOrderWallet.get("waitpay_count")+"个");
        orderStatus.add(waitPay);

        Map<String, Object> cancel = new HashMap<>();
        cancel.put("name", "取消订单");
        cancel.put("value", stasticsOrderWallet.get("cancel_count"));
//        waitPay.put("labelText", "取消订单:"+ stasticsOrderWallet.get("cancel_count")+"个");
        orderStatus.add(cancel);

        Map<String, Object> available = new HashMap<>();
        available.put("name", "待使用");
        available.put("value", stasticsOrderWallet.get("available_count"));
//        waitPay.put("labelText", "待使用:"+ stasticsOrderWallet.get("available_count")+"个");
        orderStatus.add(available);

        Map<String, Object> paysuccess = new HashMap<>();
        paysuccess.put("name", "已支付");
        paysuccess.put("value", stasticsOrderWallet.get("paysuccess_count"));
//        waitPay.put("labelText", "已支付:"+ stasticsOrderWallet.get("paysuccess_count")+"个");
        orderStatus.add(paysuccess);

        Map<String, Object> finish = new HashMap<>();
        finish.put("name", "完成交易");
        finish.put("value", stasticsOrderWallet.get("finish_count"));
//        waitPay.put("labelText", "完成交易:"+ stasticsOrderWallet.get("finish_count")+"个");
        orderStatus.add(finish);

        res.put("orderStatusList", orderStatus);
    }


    private void myDailyOrderReport(ResportRequest request, Map<String, Object> res) {
        Long adminId = request.getAdminId();
        Integer adminType = request.getAdminType();
        String reportMonth = request.getReportMonth();

        String startMonth = reportMonth + "-01";
        Date startTime = DateUtil.parse(startMonth, "yyyy-MM-dd");
        Date endTime = DateUtil.endOfMonth(startTime);

        Long startTimestamp = startTime.getTime() / 1000;
        Long endTimestamp = endTime.getTime() / 1000;
        
        List<RetailOrderDailyStasticsVo> stasticsOrderWallet = retailSettleOrderService.getDailyOrderMonthStastics(adminId, adminType, startTimestamp, endTimestamp);
        List<String> categories = new ArrayList<>();
        List<Integer> dataCount = new ArrayList<>();
        List<BigDecimal> dataPrice = new ArrayList<>();
        List<String> days = getRangeDayOfMonth(reportMonth);
        for (String day : days) {
            categories.add(day);
            boolean searchFund = false;
            for (RetailOrderDailyStasticsVo st : stasticsOrderWallet) {
                String daily = st.getDaily();
                if (ObjectUtil.equal(day, daily)) {
                    Integer da = st.getFinishCount();
                    BigDecimal dp = st.getFinishPrice();
                    dataCount.add(da);
                    dataPrice.add(dp);
                    searchFund = true;
                }
            }

            if (searchFund == false) {
                dataCount.add(0);
                dataPrice.add(new BigDecimal("0"));
            }
        }
        
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("categories", categories);
        resMap.put("dataCount", dataCount);
        resMap.put("dataPrice", dataPrice);
        res.put("orderDailyList", resMap);

//        res.put("orderStatusList", orderStatus);
    }

    private static List<String> getRangeDayOfMonth(String reportMonth) {
        if (ObjectUtil.isNotEmpty(reportMonth)) {
            Integer year = Integer.valueOf(reportMonth.split("-")[0]);
            Integer month = Integer.parseInt(reportMonth.split("-")[1]);
            Integer days = DateUtil.lengthOfMonth(month, DateUtil.isLeapYear(year));
            System.out.println(days);

            List<String> range = new ArrayList<>();
            String currentMonth = DateUtil.format(new Date(), "yyyy-MM");
            if (ObjectUtil.equal(currentMonth, reportMonth)) {
                days = DateUtil.dayOfMonth(new Date());
            }
            for (Integer i = 1; i <= days; i++) {
                range.add((month > 9 ? month : ("0" + month)) + "-" + (i > 9 ? i + "" : ("0" + i)));
            }
            return range;
        }

        return null;
    }
}
